<template>
	<div class="company">
		<list-title :data="header"></list-title>
		<el-form :model="companyForm" :rules="rules" ref="companyForm" label-width="200px">
			<el-form-item label="企业名称" prop="company.company_name" style="width: 520px;">
				<el-input v-model="companyForm.company.company_name" placeholder="企业名称"></el-input>
			</el-form-item>
			<el-form-item label="企业简介" prop="company.company_profile" style="width: 728px;">
				<el-input type="textarea" v-model="companyForm.company.company_profile" placeholder="企业简介" rows="5"></el-input>
			</el-form-item>
			<el-form-item label="营业执照" prop="company.business_license" style="width: 520px;">
				<el-input v-model="companyForm.company.business_license" placeholder="营业执照"></el-input>
			</el-form-item>
			<el-form-item label="区域" style="width: 900px;" required>
				<el-col :span="5">
					<el-form-item prop="company.province" style="margin-bottom: 0px">
						<el-select v-model="checkProvince" placeholder="请选择省" @change="getCityByProvince('')">
							<el-option v-for="(item, index) in provinceList" :key="index" :label="item.areaname" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col class="line" :span="1">-</el-col>
				<el-col :span="5">
					<el-form-item prop="company.city" style="margin-bottom: 0px">
						<el-select v-model="checkCity" placeholder="请选择市" @change="getDistrictByCity('')">
							<el-option v-for="(item, index) in cityList" :key="index" :label="item.areaname" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col class="line" :span="1">-</el-col>
				<el-col :span="12">
					<el-form-item prop="company.district" style="margin-bottom: 0px">
						<el-select v-model="checkDistrict" placeholder="请选择区">
							<el-option v-for="(item, index) in districtList" :key="index" :label="item.areaname" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
			</el-form-item>
			<el-form-item label="详细地址" prop="company.address" style="width: 520px;">
				<el-input v-model="companyForm.company.address" placeholder="详细地址"></el-input>
			</el-form-item>
			<el-form-item label="邮编" prop="company.zipcode" style="width: 520px;">
				<el-input v-model="companyForm.company.zipcode" placeholder="邮编"></el-input>
			</el-form-item>
			<el-form-item label="联系人" v-for="(item, index) in companyForm.company.contacts" :key="index" style="width: 900px;">
				<el-col :span="5">
					<el-form-item prop="company.contacts" style="margin-bottom: 0px">
						<el-input v-model="companyForm.company.contacts[index]" placeholder="姓名"></el-input>
					</el-form-item>
				</el-col>
				<el-col class="line" :span="1">-</el-col>
				<el-col :span="5">
					<el-form-item prop="company.phones" style="margin-bottom: 0px">
						<el-input v-model="companyForm.company.phones[index]" placeholder="手机"></el-input>
					</el-form-item>
				</el-col>
				<el-col class="line" :span="1">-</el-col>
				<el-col :span="10">
					<el-form-item prop="company.emails" style="margin-bottom: 0px">
						<el-input v-model="companyForm.company.emails[index]" placeholder="邮箱"></el-input>
					</el-form-item>
				</el-col>
				<el-col class="line" :span="2">
					<el-button type="text" size="small"
					icon="el-icon-plus" v-if="index==0"
					style="padding: 9px 15px 8px"
					@click="addContact">增加</el-button>
					<el-button type="text" size="small"
					icon="el-icon-delete" v-if="index>0"
					style="padding: 9px 15px 8px; color:#F56C6C"
					@click.prevent="removeContact(item)">刪除</el-button>
				</el-col>
			</el-form-item>
			<div v-if="!$route.query.id">
				<el-form-item label="管理员账号" prop="admin.username" style="width: 520px;">
					<el-input v-model="companyForm.admin.username" placeholder="管理员账号"></el-input>
				</el-form-item>
				<el-form-item label="管理员密码" prop="admin.password" style="width: 520px;" required>
					<el-input type="password" v-model="companyForm.admin.password" placeholder="管理员密码"></el-input>
				</el-form-item>
				<el-form-item label="确认密码" prop="admin.passwordConfirm" style="width: 520px;" required>
					<el-input type="password" v-model="companyForm.admin.passwordConfirm" placeholder="确认密码"></el-input>
				</el-form-item>
			</div>
			<el-form-item>
				<el-button type="primary" @click="submitForm('companyForm')" :disabled='companyForm.submitLock'>
					确 定 <span class="el-icon-loading" v-if='companyForm.submitLock'></span>
				</el-button>
				<el-button @click="resetForm('companyForm')" v-if='companyForm.company.comid==0'>重 置</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
import ListTitle from "pc/common/Title"
export default {
	data() {
		var validatePass = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('请输入密码'));
			} else {
				if (this.companyForm.admin.password !== '') {
					this.$refs.companyForm.validateField('password');
				}
				callback();
			}
		};
		var validatePass2 = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('请再次输入密码'));
			} else if (value !== this.companyForm.admin.password) {
				callback(new Error('两次输入密码不一致!'));
			} else {
				callback();
			}
		};
		return {
			/*头部数据*/
			header: {
				title: '添加企业',
				reload: false,
				buttons: [
					{
						title: '企业列表',
						type: 'primary',
						pathName: 'pc/company/company/CompanyList',
					}
				]
			},
			provinceList: [],//省份
			cityList: [],//城市
			districtList: [],//区
			companyForm: {
				submitLock: false,
				maxContactsNum: 3,//最多的联系人数目
				company: {
					comid: '',
					company_name: '',
					company_profile: '',
					business_license: '',
					province: '',
					city: '',
					district: '',
					address: '',
					zipcode: '',
					contacts: [''],
					phones: [''],
					emails: [''],
				},
				admin: {
					username: '',
					password: '',
					passwordConfirm: '',
				}
			},
			rules: {
				company: {
					company_name: [
						{ required: true, message: '请输入企业名称', trigger: 'blur' },
						{ min: 3, max: 16, message: '长度在 3 到 16 个字符', trigger: 'blur' }
					],
					province: [
						{ required: true, message: '请选择省份', trigger: 'change' }
					],
					city: [
						{ required: true, message: '请选择市', trigger: 'change' }
					],
					district: [
						{ required: true, message: '请选择区', trigger: 'change' }
					],
				},
				admin: {
					username: [
						{ required: true, message: '请输入管理员账号', trigger: 'blur' },
						{ min: 3, max: 16, message: '长度在 3 到 16 个字符', trigger: 'blur' }
					],
					password: [
						{ validator: validatePass, trigger: 'blur' }
					],
					passwordConfirm: [
						{ validator: validatePass2, trigger: 'blur' }
					],
				}
			}
		};

	},
	components: {
		ListTitle,
	},
	created: function() {
		/*获取所有省份数据*/
		this.getProvinceList()
		/*如果是修改，取出旧数据*/
		if(this.$route.query.id){
			this.getCompany(this.$route.query.id)
		}
	},
	methods: {
		/*获取所有省份数据*/
		getProvinceList: function(){
			this.$get(this.$api.provinceList).then(res => {
				// console.log(res);
				if(res.data.code === 0){
					if(res.data.data != undefined){
						this.provinceList = res.data.data
					}
				}
			})
			.catch(err => {})
			.finally(() => {})
		},
		/*根据省份ID获取城市数据*/
		getCityByProvince: function(val){
			if(val == ''){
				this.companyForm.company.city = ''//清空已经选择的城市数据
			}else{
				this.companyForm.company.city = val//修改数据的时候，有默认的数据
			}
			this.cityList = []//清空所有的城市，因为需要更新数据
			this.companyForm.company.district = ''//清空已经选择的区数据
			this.districtList = []//清空所有的区，因为需要更新数据
			if(this.companyForm.company.province != ''){
				this.$get(this.$api.cityList, {
					'id': this.companyForm.company.province
				}).then(res => {
					// console.log(res);
					if(res.data.code === 0){
						if(res.data.data != undefined){
							this.cityList = res.data.data
						}
					}
				})
				.catch(err => {})
				.finally(() => {})
			}
		},
		/*根据城市ID获取区数据*/
		getDistrictByCity: function(val){
			if(val == ''){
				this.companyForm.company.district = ''//清空已经选择的区数据
			}else{
				this.companyForm.company.district = val//修改数据的时候，有默认的数据
			}
			this.districtList = []//清空所有的区，因为需要更新数据
			if(this.companyForm.company.city != ''){
				this.$get(this.$api.districtList, {
					'id': this.companyForm.company.city
				}).then(res => {
					// console.log(res);
					if(res.data.code === 0){
						if(res.data.data != undefined){
							this.districtList = res.data.data
						}
					}
				})
				.catch(err => {})
				.finally(() => {})
			}
		},
		/*增加联系人*/
		addContact() {
			if(this.companyForm.company.contacts.length < this.companyForm.maxContactsNum){
				this.companyForm.company.contacts.push('');
				this.companyForm.company.phones.push('');
				this.companyForm.company.emails.push('');
			}
		},
		/*删除联系人*/
		removeContact(item) {
			var index = this.companyForm.company.contacts.indexOf(item)
			if (index !== -1) {
				this.companyForm.company.contacts.splice(index, 1)
				this.companyForm.company.phones.splice(index, 1)
				this.companyForm.company.emails.splice(index, 1)
			}
		},
		/*取出需要修改的数据*/
		getCompany: function() {
			this.header.title = '编辑企业'
			/*取出需要修改的数据*/
			this.companyForm.submitLock = true;
			this.$get(this.$api.modifyCompany, {
				'id': this.$route.query.id
			}).then(res => {
				if(res.data.code == 10007){//后台提示需要登录
					this.$cookie.remove('isLogin');//刪除cookie登录信息
					this.reload();
				}
				if(res.data.code == 0){
					// console.log(res.data.data)
					this.companyForm.company.comid = res.data.data.comid
					this.companyForm.company.company_name = res.data.data.company_name
					this.companyForm.company.company_profile = res.data.data.company_profile
					this.companyForm.company.business_license = res.data.data.business_license
					this.companyForm.company.province = res.data.data.province
					this.companyForm.company.city = res.data.data.city
					this.companyForm.company.district = res.data.data.district
					this.companyForm.company.address = res.data.data.address
					this.companyForm.company.zipcode = res.data.data.zipcode
					this.companyForm.company.contacts = res.data.data.contacts.split(',')
					this.companyForm.company.phones = res.data.data.phones.split(',')
					this.companyForm.company.emails = res.data.data.emails.split(',')
					/*如果已经选择了省，则需要取出市数据*/
					if(res.data.data.province != ''){
						this.getCityByProvince(res.data.data.city)
					}
					if(res.data.data.city != ''){
						this.getDistrictByCity(res.data.data.district)
					}
				}else{
					this.$message({
						showClose: true,
						message: res.data.info,
						type: 'error'
					});
				}
				this.companyForm.submitLock = false;
			})
			.catch(err => {})
			.finally(() => {}) 
		},
		/*提交添加、修改表单*/
		submitForm(formName) {
			if(!this.companyForm.submitLock){
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.companyForm.submitLock = true;
						/*添加、修改分类*/
						let apiUrl = this.$api.addCompany//默认是添加
						if(this.companyForm.company.comid != ''){//修改
							apiUrl = this.$api.modifyCompany
						}
						/*添加企业*/
						this.$post(apiUrl, {
							Company: this.companyForm.company,
							Admin: this.companyForm.admin
						}).then(res => {
							// console.log(res);
							/*成功*/
							if(res.data.code == 0){
								this.$message({
									showClose: true,
									message: res.data.info,
									type: 'success'
								});
								if(this.companyForm.company.comid != ''){
									this.$router.go(-1)	
								}else{
									this.$refs[formName].resetFields();
								}
							}else{
								this.$message({
									showClose: true,
									message: res.data.info,
									type: 'error'
								});
							}
							this.companyForm.submitLock = false;
						});
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			}
		},
		/*重置表单*/
		resetForm(formName) {
			this.$refs[formName].resetFields();
		}
	},
	computed: {
		/*验证省份是否已经获取到，有了数据才展示,防止直接出现数字，比较尴尬*/
		checkProvince: {
			get: function () {
				if(this.provinceList.length > 0){
					return this.companyForm.company.province
				}else{
					return ''
				}
			},
			set: function (val) {
				this.companyForm.company.province = val
			}
		},
		/*验证城市是否已经获取到，有了数据才展示,防止直接出现数字，比较尴尬*/
		checkCity: {
			get: function () {
				if(this.cityList.length > 0){
					return this.companyForm.company.city
				}else{
					return ''
				}
			},
			set: function (val) {
				this.companyForm.company.city = val
			}
		},
		/*验证区是否已经获取到，有了数据才展示,防止直接出现数字，比较尴尬*/
		checkDistrict: {
			get: function () {
				if(this.districtList.length > 0){
					return this.companyForm.company.district
				}else{
					return ''
				}
			},
			set: function (val) {
				this.companyForm.company.district = val
			}
		}
	}
};
</script>

<style lang="stylus" scoped>
.company
	form
		margin-top: 10px
		.line
			text-align: center
</style>